<?php
/*
 * @Description:  用户应用层
 * @Author: franktrue 807615827@qq.com
 * @Date: 2021-07-13 13:05:58
 * @LastEditTime: 2021-07-13 16:31:10
 */
namespace App\Http\Controller;

use App\Model\Entity\ShopMember;
use App\Rpc\Lib\AccountUserInterface;
use Swoft\Db\DB;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Rpc\Client\Annotation\Mapping\Reference;

/**
 * Class AuthController
 *
 * @since 2.0
 *
 * @Controller(prefix="auth")
 */
class AuthController 
{

    /**
     * @Reference(pool="accountUser.pool")
     *
     * @var AccountUserInterface
     */
    private $accountUserService;

    /**
     * @RequestMapping(route="", method={"GET"})
     *
     * @return array
     */
    public function index(Request $request)
    {
        $serverParams = $request->getServerParams();
        // var_dump($serverParams);
        return $serverParams;
    }

    /**
     * @RequestMapping(route="register", method={"POST"})
     *
     * @return array
     */
    public function register(Request $request, Response $response)
    {
        $data = $request->input();
        $serverParams = $request->getServerParams();
        return DB::transaction(function () use($data, $serverParams) {
            $res =  $this->accountUserService->register(
                $data['type'], 
                $data['account'], 
                $data['password'], 
                $serverParams['remote_addr']??''
            );
            if($res['code'] === 0) {
                $member = new ShopMember();
                $member->setUid($res['data']['id']);
                $member->setNickname($data['account']);
                $member->save();
                return ['code' => 0, 'msg' => '注册成功', 'data' => $member];;
            }
            return $res;
        });
    }

    /**
     * @RequestMapping(route="login", method={"POST"})
     *
     * @return array
     */
    public function login(Request $request, Response $response)
    {
        $data = $request->input();
        /**
         * 短信验证
         */
        $serverParams = $request->getServerParams();
        return  $this->accountUserService->login(
            $data['type'], 
            $data['account'], 
            $data['password'], 
            $serverParams['remote_addr']??''
        );
    }
}